<?php
namespace WXAPI\Controller;
use Think\Controller;
use WXAPI\Logic\UsersLogic;
use WXAPI\Logic\CartLogic;
use WXAPI\Controller\CartController;
class JifenController extends BaseController {

    public function _initialize(){
        parent::_initialize();
        $this->userLogic = new UsersLogic();
    }
    //进入打卡页面获取到的信息
    public function getJifen(){
        $user_id = I('put.user_id');
        $u = M('users');
        $s = M('sign_log');
        $user = $u->find($user_id);
        if(!$user){
            exit(json_encode(array('bj'=>0)));//会员不存在
        }

        $userInfo['bj'] = 1;//会员存在
        $userInfo['sign_day'] = $user['keep_sign_day'];//连续签到天数
        $userInfo['jifen'] = $user['pay_points'];//积分

        $userInfo['goods'] = M('goods')->where(array('is_hot'=>1,'prom_type'=>101,'is_on_sale'=>1))->limit(0,3)->select();
        $userInfo['url'] = SITE_URL;
        foreach($userInfo['goods'] as $k=>$v){
            $userInfo['goods'][$k]['original_img'] = SITE_URL.$v['original_img'];
        }


        $userInfo['sign'] = ($s->where(array('user_id'=>$user_id,'date'=>date('Y-n-j')))->find()) ? 1 : 0;//今天签到没
        $first = mktime(0,0,0,date('m'),1,date('Y'));
        $last  = mktime(23,59,59,date('m'),date('t'),date('Y'));
        $userInfo['signs'] = $s->where("user_id = '".$user_id."' and time between '".$first."' and '".$last."'")->select();//本月签到记录


        $date = date('Y-n-j',time()-3600*24);
        $zt = $s->where(array('user_id'=>$user_id,'date'=>$date))->find();
        if(!$zt){//昨天没签到
            $jt = $s->where(array('user_id'=>$user_id,'date'=>date('Y-n-j')))->find();
            if(!$jt){
                $u->where(array('user_id'=>$user_id))->save(array('keep_sign_day'=>0));//修改连续签到天数
                $userInfo['sign_day'] = 0;
            }else{
                $u->where(array('user_id'=>$user_id))->save(array('keep_sign_day'=>1));//修改连续签到天数
                $userInfo['sign_day'] = 1;
            }
        }else{
            $userInfo['sign_day'] = $user['keep_sign_day'];
        }
		$sign_date=M('sign_log')->field('date')->where("user_id ={$user_id}")->select();
        if ($sign_date) {
            foreach ($sign_date as $k => $v) {
              $str = strtotime($v['date']);
                $signdate[] =date('Y-n-j',$str);
            }
        }
		 $userInfo['signdate'] = $signdate;
		 $jf = M('sign_in')->find();
		if(!$jf['sign_type']){
			$userInfo['sign_jifen'] = $jf['sign_points'];
			$in_sign1 = json_decode($jf['sign']);
			$in_sign2 = json_decode($jf['score']);
			$user = $u->find($user_id);
			if(in_array(($user['keep_sign_day']+1),$in_sign1)){
				$score = array();
				foreach($in_sign1 as $k=>$v){
					$score[$v] = $in_sign2[$k];
				}
				$userInfo['sign_jifen'] += $score[($user['keep_sign_day']+1)];
			}
		}else{
			$userInfo['sign_jifen'] = 0;
		}
		exit(json_encode($userInfo));
    }


    //签到操作
    public function sign(){
        $u = M('users');
        $s = M('sign_log');
        $user_id = I('put.user_id');
        $user = $u->find($user_id);
        if(!$user){
            exit(json_encode(array('bj'=>0)));//会员不存在
        }
        $date = date('Y-n-j');
        $sign = $s->where(array('user_id'=>$user_id,'date'=>$date))->find();
        if(!$sign){
            $jf = M('sign_in')->find();
            if(!$jf['sign_type']){
                $jifen = $jf['sign_points'];
                $in_sign1 = json_decode($jf['sign']);
                $in_sign2 = json_decode($jf['score']);
            }else{
                $jifen = 0;
            }
            $s->add(array('user_id'=>$user_id,'date'=>$date,'time'=>time()));
            //$u->where(array('user_id'=>$user_id))->setInc( 'pay_points',$jifen);
			accountLog($user_id, 0 , $jifen ,"签到赠送积分");
            exit(json_encode(array('bj'=>1,'jifen'=>$jifen,'sign_date'=> date('Y-n-j'))));//签到成功
        }else{
            exit(json_encode(array('bj'=>2)));//重复签到
        }
    }

    //查看其他月份的签到信息
    public function getSignByMonth(){
        $user_id = I('put.user_id');
        $m = I('put.m');
        $y = I('put.y');
        $u = M('users');
        $s = M('sign_log');
        $user = $u->find($user_id);
        if(!$user){
            exit(json_encode(array('bj'=>0)));//会员不存在
        }

        $userInfo['bj'] = 1;
        $first = mktime(0,0,0,$m,1,$y);
        $last  = mktime(23,59,59,$m,date('t'),$y);
        $userInfo['signs'] = $s->where("user_id = '".$user_id."' and time between '".$first."' and '".$last."'")->select();//本月签到记录
        exit(json_encode($userInfo));
    }
    //积分商城首页展示信息
    public function jifenShop(){
        $u = M('users');
        // $user_id = I('put.user_id');
        // dump($user_id);
        $user_id = $_POST['user_id'];
        $user = $u->find($user_id);
        // dump($user_id);
        if(!$user){
            exit(json_encode(array('bj'=>0)));//会员不存在
        }
        $info['bj'] = 1;
        $info['jifen'] = $user['pay_points'];
        //$pid = M('ad_position')->where(array('position_name'=>'积分商城banner轮播图'))->getField('position_id');
        $info['images'] = M('ad')->where(array('pid'=>51319,'enabled'=>1))->select();
        foreach($info['images'] as $k=>$v){
            $info['images'][$k]['ad_code'] = SITE_URL.$v['ad_code'];
        }
        $info['type'] = M('jifen_type')->order('sort_type')->select();
        array_unshift($info['type'],array('type_id'=>0,'type_name'=>'全部'));
        foreach($info['type'] as $k=>$v){
            $info['type'][$k]['xb'] = $k;
        }
        $info['goods'] = M('goods')->where(array('prom_type'=>101,'is_on_sale'=>1))->order('store_count','desc')->limit(0,10)->select();
        foreach($info['goods'] as $k=>$v){
            $info['goods'][$k]['original_img'] = SITE_URL.$v['original_img'];
        }
        exit(json_encode($info));
    }

    public function getGoods(){
        $result = file_get_contents("php://input");
        $data = json_decode($result, true);
        $type_id = $data['type_id']?$data['type_id']:0;
        $page = $data['page']?$data['page']:0;
        $som = $page*10;
        $g = M('goods');
        // if($type_id == 0){
        //     $count = $g->where(array('prom_type'=>101,'is_on_sale'=>1))->count();
        // }else{
        //     $count = $g->where(array('prom_type'=>101,'is_on_sale'=>1,'jifen_type'=>$type_id))->count();
        // }
        // if($count > $som){
        //     $goods['status'] = 1;
        //     if($type_id == 0){
        //         $goods['goods'] = $g->where(array('prom_type'=>101,'is_on_sale'=>1))->limit($som,10)->select();
        //     }else{
        //         $goods['goods'] = $g->where(array('prom_type'=>101,'is_on_sale'=>1,'jifen_type'=>$type_id))->limit($som,10)->select();
        //     }
        // }else{
        //     $goods['status'] = 0;
        // }
        //未分页
        $goods['status'] = 1;
        if($type_id == 0){
            $goods['result'] = $g->where(array('prom_type'=>101,'is_on_sale'=>1))->order('sorts asc')->limit($som,10)->select();
        }else{
            $goods['result'] = $g->where(array('prom_type'=>101,'is_on_sale'=>1,'jifen_type'=>$type_id))->order('sorts asc')->limit($som,10)->select();
        }
        foreach($goods['result'] as $k=>$v){
            $goods['result'][$k]['original_img'] = SITE_URL.$v['original_img'];
        }
        exit(json_encode($goods));
    }

    public function cart(){
        $goods_id = I('goods_id');
        $goods_num = I('goods_num');
        $goods_spec = I('goods_spec');
        $user_id = I('user_id');
        //会员信息
        $usersInfo = M('users')->find($user_id);

        //购物车列表
        $goods = M('goods')->find($goods_id);
        $cart[0] = $goods;
        $cart[0]['goods_num'] = $goods_num;
        
        foreach($cart as $k=>$v){
            $cart[$k]['original_img'] = SITE_URL.$v['original_img'];
        }

        // 收货地址
        $addresslist = M('UserAddress')->where("user_id = {$user_id}")->select();
        $c = M('UserAddress')->where("user_id = {$user_id} and is_default = 1")->count(); // 看看有没默认收货地址       
        
        if ((count($addresslist) > 0) && ($c == 0)) // 如果没有设置默认收货地址, 则第一条设置为默认收货地址
            $addresslist[0]['is_default'] = 1;
        else if (count($addresslist) > 0) 
        {
            $addresslist[0] = M('UserAddress')->where("user_id = {$user_id} and is_default = 1")->find();
        }

        //计算邮费
        if($goods['is_free_shipping']){
             $shippingPrice = 0;//包邮
        }else{
            if($addresslist[0]){
                $weight = (float)$goods['weight'] * (int)$goods_num;
                $shippingPrice = $this->cart_freight('yuantong',$addresslist[0]['province'],$addresslist[0]['city'],$addresslist[0]['district'],$weight);
            }else{
                $shippingPrice = 0;
            }
        }

        // 支付方式 
        $paymentList = M('Plugin')->where("`type` = 'payment' and status = 1")->select();
        foreach ($cart as $k=>$v){
            $cart[$k]['image'] = $v['original_img'];
        }
        // $points = M("config")->where(array("name"=>"point_rate"))->getField("value");
        $json_arr = array(
            'status' => 1,
            'msg' => '获取成功',
            'result' => array(
                'addressList' => $addresslist[0], // 收货地址
                'cartList' => $cart, // 购物车列表
                'totalPrice' => $shippingPrice, // 总计
                'totalJifen' => (int)$goods['jifen_price']*(int)$goods_num, // 总积分
                'userInfo' => $usersInfo, // 用户详情
                "express_price"=>$shippingPrice,
                "paymentList"  =>$paymentList
            ));
        exit(json_encode($json_arr));
    }

    //运费计算
    public function cart_freight($shipping_code,$province,$city,$district,$weight){
        
        if($weight == 0) return 0; // 商品没有重量
        if($shipping_code == '') return 0;               
      
       // 先根据 镇 县 区找 shipping_area_id   
          $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  ".C('DB_PREFIX')."shipping_area where shipping_code = '$shipping_code') and region_id = {$district} and store_id = -1")->getField('shipping_area_id');
        
        // 先根据市区找 shipping_area_id
       if($shipping_area_id == false)    
          $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  ".C('DB_PREFIX')."shipping_area where shipping_code = '$shipping_code') and region_id = {$city} and store_id = -1")->getField('shipping_area_id');

       // 市区找不到 根据省份找shipping_area_id
       if($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  ".C('DB_PREFIX')."shipping_area where shipping_code = '$shipping_code') and region_id = {$province} and store_id = -1")->getField('shipping_area_id');

       // 省份找不到 找默认配置全国的物流费
       if($shipping_area_id == false)
       {           
            // 如果市和省份都没查到, 就查询 tp_shipping_area 表 is_default = 1 的  表示全国的  select * from `tp_plugin`  select * from  `tp_shipping_area` select * from  `tp_area_region`           
           $shipping_area_id = M("ShippingArea")->where("shipping_code = '$shipping_code' and is_default = 1 and store_id = -1")->getField('shipping_area_id');
       }
       if($shipping_area_id == false)
           return 0;
       /// 找到了 shipping_area_id  找config       
       $shipping_config = M('ShippingArea')->where("shipping_area_id = $shipping_area_id")->getField('config');
       $shipping_config  = unserialize($shipping_config);
       $shipping_config['money'] = $shipping_config['money'] ? $shipping_config['money'] : 0;
       // echo $weight;
       // 1000 克以内的 只算个首重费
       if($weight < $shipping_config['first_weight'])
       {          
            // echo 1;die;
           return $shipping_config['money'];     
       }
       // 超过 1000 克的计算方法 
       $weight = $weight - $shipping_config['first_weight']; // 续重
       $weight = ceil($weight / $shipping_config['second_weight']); // 续重不够取整 
       $freight = $shipping_config['money'] +  $weight * $shipping_config['add_money']; // 首重 + 续重 * 续重费       
       // die;
       return $freight;  
    }

    public function addOrder(){

        $goods_id = I('goods_id');
        $goods_num = 1;
        $goods_spec = I('goods_spec');
        $address_id = I('address_id');
        $user_money = I('user_money');
        // $pay_points = I('put.pay_points');
        $pay_points = 0;
        $pay_code = I('pay_code');
        // $couponCode = I('put.couponCode');
        // $couponTypeSelect = I('put.couponTypeSelect');
        // $coupon_id = I('put.coupon_id');
        $shippingPrice = I('shippingPrice');
        $totalJifen = I('totalJifen');
        $user_id = I('user_id');

        //会员信息
        $usersInfo = M('users')->find($user_id);
        if($usersInfo['pay_points'] < ($totalJifen+$pay_points)){
            exit(json_encode(array('status'=>-7,'msg'=>'积分不足','result'=>'')));
        }
        $order_count = M('Order')->where("user_id= '$user_id' and order_sn like '".date('Ymd')."%'")->count(); // 查找购物车商品总数量
        if($order_count >= 50){
            exit(json_encode(array('status'=>-9,'msg'=>'一天只能下50个订单','result'=>'')));
        }

        //购物车列表
        $goods = M('goods')->where(['goods_id'=>$goods_id])->find();
        // var_dump($goods);
        // die;
        if(empty($goods['is_on_sale'])){
            exit(json_encode(array('status'=>-9,'msg'=>'商品下架了','result'=>'')));
        }
        if($goods['store_count'] < $goods_num){
            exit(json_encode(array('status' =>-8,'msg'=>'库存不足','result'=>'')));
        }
        $totalJifen = (int)$goods['jifen_price']*(int)$goods_num;
        
        
        // $address = M('UserAddress')->where("address_id = $address_id")->find();

        $users_dizi = M('users')->where("user_id = $user_id")->find();
        //生成订单
        $cartL = new CartLogic();
        $order_sn = $cartL->get_order_sn();
        empty($master_order_sn) && ($master_order_sn = $cartL->get_order_sn());

        $data = array(
            'order_sn'         =>$order_sn, // 订单编号
            'master_order_sn'  =>$master_order_sn, // 主订单编号
            'user_id'          =>$user_id, // 用户id
            'consignee'        =>(string)$users_dizi['nickname'], // 收货人
            // 'province'         =>$address['province'],//'省份id',
            // 'city'             =>$address['city'],//'城市id',
            // 'district'         =>$address['district'],//'县',
            // 'twon'             =>$address['twon'],// '街道',
            'address'          =>$users_dizi['company_address'],//'详细地址',
            'mobile'           =>$users_dizi['mobile'],//'手机',
            // 'zipcode'          =>$address['zipcode'],//'邮编',            
            // 'email'            =>$address['email'],//'邮箱',
            'shipping_code'    =>'shentong',//'物流编号',
            'shipping_name'    =>'申通', //'物流名称',
            'user_note'        =>'', //'给卖家留言',
            'goods_price'      =>0,//每个店铺的商品价格',
            // 'shipping_price'   =>$shipping_price,//'物流价格',                
            'user_money'       =>$user_money, // 当前订单使用的余额数量
            // 'coupon_price'     =>$car_price['store_coupon_price'][$k],//'使用优惠券',                        
            'integral'         =>$totalJifen, // 使用的积分数量
            'total_amount'     =>$shippingPrice,// 订单总额 = 商品总价 + 物流费
            'order_amount'     =>$shippingPrice-$user_money,//'应付款金额',                
            'add_time'         =>time(), // 下单时间                
            'order_prom_type'  =>101,//'订单优惠活动类别',
            'pay_code'         =>'jifen',
            );
            // dump($data);exit;
        $order_id = M("Order")->data($data)->add();

        //添加订单商品
        $data2['order_id']           = $order_id; // 订单id
        $data2['goods_id']           = $goods_id; // 商品id
        $data2['goods_name']         = $goods['goods_name']; // 商品名称
        $data2['goods_sn']           = $goods['goods_sn']; // 商品货号
        $data2['goods_num']          = $goods_num; // 购买数量
        $data2['jifen_price']        = $goods['jifen_price']; // 市场价
        // $data2['goods_price']        = $val['goods_price']; // 商品价
        // $data2['spec_key']           = $goods_spec; // 商品规格
        // $data2['spec_key_name']      = M('spec_goods_price')->where(['key'=>$goods_spec])->getField('key_name'); // 商品规格名称
        $data2['prom_type']          = 101; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
        $order_goods_id              = M("OrderGoods")->data($data2)->add();
        logOrder($order_id,'您提交了订单，请等待系统确认','提交订单',$user_id,2);

        // 如果应付金额为0  可能是余额支付 + 积分 + 优惠券 这里订单支付状态直接变成已支付 
        if($data['order_amount'] == 0)
        {                        
            update_pay_status($order_sn, 1);
        }
        // if(!empty($coupon_id[$k])){
        //     // 2修改优惠券状态
        //     $data3['uid'] = $user_id;
        //     $data3['order_id'] = $order_id;
        //     $data3['use_time'] = time();
        //     M('CouponList')->where("id = {$coupon_id[$k]}")->save($data3);
        //     $cid = M('CouponList')->where("id = $coupon_id[$k]")->getField('cid');
        //     M('Coupon')->where("id = $cid")->setInc('use_num'); // 优惠券的使用数量加一
        // }
        
        // 3 扣除积分 扣除余额
        $jifen = $pay_points+$totalJifen;
        M('Users')->where("user_id = $user_id")->setDec('pay_points',$jifen); // 用户的积分减
        M('Users')->where("user_id = $user_id")->setDec('user_money',$user_money); // 用户的余额减

        // 5 记录log 日志
        $data4['user_id'] = $user_id;
        $data4['user_money'] = -$user_money;
        $data4['pay_points'] = -($pay_points+$totalJifen);
        $data4['change_time'] = time();
        $data4['desc'] = '下单消费';
        $data4['order_sn'] = $order_sn;
        $data4['order_id'] = $order_id;    
        // 如果使用了积分或者余额才记录
        ($data4['user_money'] || $data4['pay_points']) && M("AccountLog")->add($data4);

        // 如果有微信公众号 则推送一条消息到微信
        if($usersInfo['oauth']== 'weixin')
        {
            $wx_user = M('wx_user')->find();
            $jssdk = new \Mobile\Logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
            $wx_content = "你刚刚下了一笔订单:{$order_sn} 尽快支付,过期失效!";
            $jssdk->push_msg($usersInfo['openid'],$wx_content);
        }
        // if($payment=="cod"){
        //     $result['data']['pay_money']=0;
        // }
        $order = M('order')->where(array("master_order_sn"=>$master_order_sn))->select();
        $cartC = new CartController();
        $result['data'] = $cartC->getWXPayInfo($master_order_sn);
        //如果是选的货到付款，暂时不需要付款
        if($pay_code=="cod"){
            $result['data']['pay_money']=0;
        }
        $result['status'] = 1;
        $result['result'] = $master_order_sn;
        $result['order'] = $order;
        $result['msg'] = '提交订单成功';

        exit(json_encode($result));
    }
    
    /*
     * 用户订单列表
     */
    public function getOrderList(){
        $this->user_id = I('user_id',0);
        $prom_type = I('prom_type',0);
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $page = I('page','');
        $type = I('type','');
		$keys=I('keys','');

        if($type == "NO")
        	$type = "";

            $map = " 1 ";
            $map .= " and a.user_id = {$this->user_id} ";
            $map .= " and a.order_status != 3 ";
            $map .= " and b.is_order_refund != 1 ";
            $map .= " and a.order_prom_type={$prom_type}";
			if($keys)
			$map .= " and (goods_name like '%".$keys."%' or order_sn like '%".$keys."%' or master_order_sn like '%".$keys."%') ";
			
			$db_prefix = C('DB_PREFIX');
              if ($type == "AFTERSALE"){
                  $count = M('return_goods as a')
				  ->field('a.*,b.*')
				  ->join($db_prefix.'goods as b on a.goods_id = b.goods_id','LEFT')
				  ->where("a.user_id = {$this->user_id}")->count();
                  $Page = new \Think\Page($count,10);

                  $show = $Page->show();

                  $Page->firstRow = $Page->listRows * $page;

                  $order_list =  M('return_goods as a')
				  ->field('a.*')
				  ->where("a.user_id = {$this->user_id}")->order("a.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
              }else{
                  //条件搜索
                  if($type == "FINISH"){
                      $map1 = ' AND (order_status=2 or order_status=4) ';
                      $map = $type ? $map.$map1 : $map;
                  }else{
                      $map = $type ? $map.C($type) : $map;
                  }
     
                  $count = M('order as a')
				  ->field('a.*,b.*')
				  ->join($db_prefix.'order_goods as b on b.order_id = a.order_id')
				  ->group('a.order_id')->where($map)->count();
                  $Page       = new \Think\Page($count,10);

                  $show = $Page->show();

                  $Page->firstRow = $Page->listRows * $page;
                  //echo $page;
                  //echo $Page->firstRow;

                  $order_list =  M('order as a')
				  ->field('a.*,b.*')
				  ->join($db_prefix.'order_goods  as  b  on b.order_id = a.order_id')
				  ->group('a.order_id')
				  ->where($map)->order("a.order_id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
                //   dump(M()->getLastSql());
              }

              //获取订单商品
              foreach($order_list as $k=>$v){
				  
                  $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
				  $order_list[$k]['order_amount'] +=$v['yijia_heji'];
				  $order_list[$k]['total_amount'] +=$v['yijia_heji']; 
                  //订单总额
                  //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount'];
                  if ($type == "AFTERSALE"){
					  
                  $goods_list =  M('return_goods as a')
				  ->field('a.*,b.goods_name,b.original_img')
				  ->join($db_prefix.'goods as b on a.goods_id = b.goods_id','LEFT')
				  ->where("a.user_id = {$this->user_id} and a.store_id={$v['store_id']}")->order("a.id desc")->select();
                  foreach ($goods_list as $key => $value)
                  {
                      $goods_list[$key]['heji'] = \sanwei(($value['member_goods_price']+$value['yijia'])*$value['goods_num']);
					  $goods_list[$key]['shijian'] = date('Y/m/d H:i',$value['addtime']);
                  }
                      $data['result'] = $goods_list;

                  }else{
						$data = $this->userLogic->get_order_goods($v['order_id']);
                  }

                  foreach ($data['result'] as $key => $value)
                  {
                      $data['result'][$key]['image'] = SITE_URL.get_spec_img($value['spec_key'],$value['original_img']);
                  }

                  $order_list[$k]['goods_list'] = $data['result'];
              }

        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$order_list)));
    }
}